// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package cn.xiuxius.embedded.runconfig;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessHandlerFactory;
import com.intellij.execution.process.ProcessTerminatedListener;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;

public class EasySTCRunConfiguration extends RunConfigurationBase<EasySTCRunConfigurationOptions> {

  protected EasySTCRunConfiguration(Project project,
                                    ConfigurationFactory factory,
                                    String name) {
    super(project, factory, name);
  }

  public EasySTCTask getTask() {
    return getOptions().getTask();
  }

  public void setTask(EasySTCTask task) {
    getOptions().setTask(task);
  }

  @Override
  protected @NotNull EasySTCRunConfigurationOptions getOptions() {
    return (EasySTCRunConfigurationOptions) super.getOptions();
  }

  @Override
  public @NotNull SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
    return new EasySTCSettingsEditor();
  }

  @Override
  public @Nullable RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment environment) {
    return new CommandLineState(environment) {
      @Override
      protected @NotNull ProcessHandler startProcess() throws ExecutionException {
        String easyStcHome = System.getenv("EASY_STC_HOME");
        if (easyStcHome == null || easyStcHome.isBlank()) {
          throw new ExecutionException("EASY_STC_HOME environment variable is not set.");
        }

        File exeFile = new File(easyStcHome, "easystc.exe");
        if (!exeFile.exists()) {
          throw new ExecutionException("Cannot find easystc.exe in EASY_STC_HOME.");
        }

        GeneralCommandLine commandLine = new GeneralCommandLine();
        commandLine.setExePath(exeFile.getAbsolutePath());
        EasySTCTask task = getTask();

        switch (task) {
          case RUN, BUILD -> {
            commandLine.addParameters(task.getCommand());
            if (getOptions().isBuildClean()) commandLine.addParameter("-c");
          }
            case FLASH -> {
            commandLine.addParameter(task.getCommand());
            if (!getOptions().getFlushPort().isBlank()) {
              commandLine.addParameter("-port");
              commandLine.addParameter(getOptions().getFlushPort());
            }
          }
          case ADV_FLASH -> {
            commandLine.addParameter(task.getCommand());
            // Future: Add advanced options here
          }
          case CLEAN -> {
            commandLine.addParameter(task.getCommand());
          }
        }

        commandLine.setWorkDirectory(getProject().getBasePath());
        OSProcessHandler handler = ProcessHandlerFactory.getInstance().createColoredProcessHandler(commandLine);
        ProcessTerminatedListener.attach(handler);
        return handler;
      }
    };
  }
}
